<template>
    <div class="upload-image-container">
        <div class="row">
            <div class="col">
                <h6>{{options.title}}
                    <small class="text-mute">允许上传文件格式：{{ extensions }}</small>
                    <small class="pull-right">您至少需要上传{{ options.min }} 个文件。
                    </small>
                </h6>
            </div>
        </div>
        <Progress v-if="percentShow" :percent="percent" status="active"></Progress>
        <div class="row no-gutters upload-item-container">
            <div class="demo-upload-list" v-for="item in fileList">
                <template>
                    <img v-if="options.type == 'image'" :src="item.url">
                    <video v-if="options.type == 'video'" :src="item.url" />
                    <div v-if="options.type == 'document'">
                        <Icon type="social-dropbox" size="30"></Icon>
                    </div>
                    <div class="demo-upload-list-cover">
                        <Icon v-if="options.type != 'document'" type="ios-eye-outline"
                              @click.native="handlePictureCardPreview(item.name,item.url)"></Icon>
                        <Icon v-if="options.type != 'document'" type="ios-compose" @click.native="handleChangeName(item)"></Icon>
                        <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                    </div>
                </template>
                <!--<template v-else>-->
                <!--<Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>-->
                <!--</template>-->
            </div>
            <Upload
                    ref="upload"
                    :show-upload-list="false"
                    :default-file-list="fileList"
                    :on-success="handleSuccess"
                    :on-progress = "handleProgress"
                    :format="['jpg','mp4','wmv','avi','zip','rar']"
                    :accept="options.ext"
                    :action="uploadAction"
                    :data="uploadFormParams"
                    :before-upload="onBeforeUpload"
                    :on-error="onError"
                    :on-format-error="handleFormatError"
                    type="drag"
                    style="display: inline-block;width:128px;">
                <div style="width: 128px;height:128px;line-height: 128px;">
                    <Icon type="android-document" size="20"></Icon>
                </div>
            </Upload>
        </div>
    </div>

</template>
<script>
  import worksApi from 'assets/js/api/works'
  import md5 from 'blueimp-md5'
  import util from 'assets/js/libs/util'

  export default {
    props: {
      options: {
        type: Object,
        default:
          {
            'title': '上传图片',
            'key': '内容',
            'exts': '.jpg',
            'min': 1,
            'max': 1,
          }
      },
      fileList: {
        type: Array,
        default: []
      },
      awardID: {
        type: Number,
        default: 0
      }

    },
    mounted () {
      this.uploadList = this.$refs.upload.fileList
    },
    data () {
      return {
        value: '',
        uploadList: [],
        dialogImageUrl: '',
        dialogVisible: false,
        percent:0,
        percentShow:false,
        uploadFormParams: {
          'key': '', //path
          'policy': '', //OssUtilities.signature.policy
          'OSSAccessKeyId': '', //OssUtilities.signature.accessid
          'success_action_status': '200', //让服务端返回200,不然，默认会返回204
          'callback': '',//OssUtilities.signature.accessid
          'signature': '' //OssUtilities.signature.signature
        },
        uploadAction: ''
      }
    },
    computed: {
      extensions () {
        return this.options.exts
      }
    },
    methods: {
      handleRemove (file) {
        this.$Modal.confirm({
          title: '删除确认',
          content: '您是否确认删除此项？',
          onOk: () => {
            const fileList = this.fileList
            this.fileList.splice(fileList.indexOf(file), 1)
            worksApi.deleteFile(file.id, () => {
              this.$Notice.success({
                title: '删除成功',
                desc: '删除成功！'
              })
            })
          }
        })
      },
      handleChangeName (item) {
        this.$Modal.confirm({
          render: (h) => {
            return h('Input', {
              props: {
                value: item.name,
                autofocus: true,
                placeholder: '请输入名称'
              },
              on: {
                input: (val) => {
                  this.value = val
                }
              }
            })
          },
          onOk: () => {
            worksApi.updateFileName(item.id, this.value, () => {
              item.name = this.value
              this.$Notice.success({
                title: '修改成功',
                desc: '修改成功！'
              })
            })
          }
        })
      },
      handleProgress(event){
        this.percent = parseInt(event.percent)
      },
      handleSuccess (file) {
        this.percentShow = false
        this.percent = 0
        this.$emit('uploaded', file)
      },
      handleFormatError (file) {
        this.$Notice.warning({
          title: '格式不正确',
          desc: '该文件格式不正确'
        });
      },
      /**
       *
       */
      handlePictureCardPreview (name, path) {
        this.$Modal.info({
          title: name,
          render: (h) => {
            let type =this.options.type === 'image'?'img':'video'
            return h(type, {
              domProps: {
                autoplay:true,
                src: path,
              },
              style: {
                width: '100%'
              },
            })
          }
        })
      },
      /**
       *
       */
      onError (e) {
        this.percentShow = false
        this.percent = 0
      },

      /**
       *
       * @param file
       * @returns {Promise<never>}
       */
      async onBeforeUpload (file) {
        // console.log(file)
        let self = this
        let reader = await util.readFileAsBinaryString(file)
        let hash = md5(reader.result)
        let [policyResponse, uploadResponse] = await Promise.all([
          worksApi.getOssUploadPolicy(),
          worksApi.perpareWorksUpload(self.awardID, file.name, self.options.key, hash)
        ])
        self.uploadFormParams.policy = policyResponse.data.policy
        self.uploadFormParams.OSSAccessKeyId = policyResponse.data.accessid
        self.uploadFormParams.callback = policyResponse.data.callback
        self.uploadFormParams.signature = policyResponse.data.signature
        self.uploadFormParams.key = uploadResponse.data.path + '/' + uploadResponse.data.name
        self.uploadAction = policyResponse.data.host
        self.percentShow = true
        console.log(uploadResponse);
        if (!uploadResponse.data.status) {
          return Promise.reject(new Error(400))
        }
      }
    }
  }
</script>
<style scoped>
    .demo-upload-list {
        display: inline-block;
        width: 130px;
        height: 130px;
        text-align: center;
        line-height: 130px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
        margin-right: 4px;
    }

    .demo-upload-list img {
        width: 100%;
        height: 100%;
    }
    .demo-upload-list video {
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, .6);
    }

    .demo-upload-list:hover .demo-upload-list-cover {
        display: block;
    }

    .demo-upload-list-cover i {
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
